package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author：cxl
 * @Package：com.hmall.common.interceptor
 * @Project：hmall-micro1
 * @name：UserInfoInterceptor
 * @Date：2025/11/13 11:48
 * @Filename：UserInfoInterceptor
 */
/*
 * 微服务的拦截器，获取请求头的用户id*/
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {
    //进入之前解析
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //读取请求头中的id
        String userIdStr = request.getHeader("user-info");
        log.info("userIdStr{}",userIdStr);
        if (StrUtil.isNotEmpty(userIdStr)) {
            //存进ThreadLocal
            UserContext.setUser(Long.parseLong(userIdStr));
        }
        return true;
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception 无论出异常都会执行remove，却博爱不会内存泄露
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        UserContext.removeUser();
    }
}
